package ywpt.service.client;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import ywpt.core.dao.HibernateEntityDao;
import ywpt.model.ClientDevice;
import ywpt.model.DeviceParts;
import ywpt.web.common.PublicFunction;

public class DevicePartsServiceImpl extends HibernateEntityDao<DeviceParts> implements DevicePartsService{
	public DevicePartsServiceImpl(){
		
	}

	@Override
	public String CreateCode(Long deviceId) {
		DetachedCriteria query = DetachedCriteria.forClass(DeviceParts.class, "parts");
		query.add(Restrictions.eq("device", this.get(ClientDevice.class, deviceId)));
		String partsCode="";
		String code="";
		Integer maxId=new Integer(0);
		query.addOrder(Order.desc("id"));
		List<DeviceParts> deviceParts = this.getDeviceParts(query);
		if ( deviceParts.iterator().hasNext() )	
		{
			code = deviceParts.iterator().next().getCode();
			maxId = new Integer(code);
		}
		partsCode=PublicFunction.getNextCode("", maxId, false,3); 
		query.setProjection(null);
		return partsCode;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<DeviceParts> getDeviceParts(DetachedCriteria query) {
		return this.findAllByCriteria(query);
	}

	@Override
	public DeviceParts getDevicePartsById(Long id) {
		return this.get(id);
	}

	@Override
	public void removeDeviceParts(Long id) {
		super.removeById(id);
	}

	@Override
	public void saveDeviceParts(DeviceParts deviceParts, Long deviceId) {
		if( deviceId != null){
			deviceParts.setDevice(this.get(ClientDevice.class, deviceId));
		}
		super.save(deviceParts);
	}

	@Override
	public void updateDeviceParts(DeviceParts deviceParts, Long deviceId) {
		if( deviceId != null){
			deviceParts.setDevice(this.get(ClientDevice.class, deviceId));
		}
		super.update(deviceParts);
		
	}
}
